//
//  KCTGPSDataSyncVC.swift
//  BLEManagerSwiftDemo
//
//  Created by Qinsz on 2019/6/10.
//  Copyright © 2019年 Qinsz. All rights reserved.
//

import UIKit

class KCTGPSDataSyncVC: UIViewController {
    
    @IBOutlet weak var responseView: UITextView!
    @IBOutlet weak var currentDataIdLabel: UILabel!
    
    private var dataId:UInt32 = 0
    private var succeedCount:UInt32 = 0
    private var totalPackCount:UInt32 = 0
    
    private var fileData:Data = Data.init()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        responseView.isEditable = false
    }


    //MARK: - 返回
    @IBAction func clickBack(_ sender: Any) {
        self.navigationController?.popViewController(animated: true)
    }
    
    //MARK: - 开始同步数据
    @IBAction func clickStartSync(_ sender: Any) {
        reqDataId()
    }
    
    
    private func reqDataId(){
        
//        SVProgressHUD.show(withStatus: "获取DataId")
//
//        let payload = KCTBLEPayloadModel.init(key: 0x01)
//
//        var pack = KCTBLEPackModel.init()
//        pack.command = 0x18
//        pack.payloadArray.append(payload)
//
//        let task = KCTBLETask.init {[weak self] (tsk,rspPacks, err) -> (Void) in
//            if let value = rspPacks?.first?.payloadArray.first?.value {
//                if value.length >= 8{
//
//                    var dataId:UInt32 = 0
//                    value.getBytes(&dataId, range: NSMakeRange(0, 4))
//                    dataId = CFSwapInt32BigToHost(dataId)
//
//                    var count:UInt32 = 0
//                    value.getBytes(&count, range: NSMakeRange(4, 4))
//                    count = CFSwapInt32BigToHost(count)
//
//                    self?.responseView.text = "获取dataId:dataId=\(dataId),totalCount=\(count)"
//                    self?.currentDataIdLabel.text = "\(dataId)"
//
//                    var startOrder:UInt32 = 0
//                    if let currentDataId = self?.dataId,let currentCount = self?.totalPackCount ,currentDataId == dataId,currentCount == count {
//                        //续传
//                        startOrder = self?.succeedCount ?? 0
//                    }
//
//                    self?.dataId = dataId
//                    self?.totalPackCount = count
//
//                    if startOrder == 0 {
//                        self?.fileData.removeAll()
//                    }
//
//                    if startOrder < count-1{
//                        SVProgressHUD.show(withStatus: "开始同步")
//                        self?.reqDatas(dataId: dataId, packOrder: startOrder)
//                    }else{
//                        SVProgressHUD.showInfo(withStatus: "没有未接收的数据")
//                    }
//
//                }else{
//                    self?.responseView.text = "获取dataId异常:value(\(value))长度不足8字节"
//                    SVProgressHUD.showError(withStatus: self?.responseView.text)
//                }
//            }else{
//                var errContent = "获取dataId失败:"
//                if let rspErr = err{
//                    errContent.append("\(rspErr)")
//                }
//                errContent.append("rspPack数据异常")
//                SVProgressHUD.showError(withStatus: errContent)
//                self?.responseView.text = errContent
//            }
//        }
//        task.blePacks.append(pack)
//        let _ = KCTNewBleManager.sharedInstance.resume(task: task)
    }
    
    //MARK:- 请求数据包
    private func reqDatas(dataId:UInt32,packOrder:UInt32){
        
        
//        KCTBLETaskGPSBin.ResumeReqData(dataId: dataId, order: packOrder) {[weak self] (err, gpsArray) -> (Void) in
//            
//            var errInfos = err?.description ?? ""
//            for index in 0 ..< gpsArray.count {
//                let model = gpsArray[index]
//                if model.errCode == 0xA1 {
//                    if self?.succeedCount == model.order {
//                        //序号正常
//                        let sucCount = model.order + 1
//                        self?.succeedCount = sucCount
//                        self?.fileData.append(model.gpsData)
//                        
//                        
//                        if let totalCount = self?.totalPackCount {
//                            self?.responseView.text = "进度:\(sucCount)/\(totalCount)"
//                            SVProgressHUD.show(withStatus: self?.responseView.text)
//                            
//                            if sucCount >= totalCount {
//                                //结束
//                                break
//                            }
//                        }else{
//                            errInfos.append(" 总包数异常")
//                            break
//                        }
//                        
//                    }else{
//                        errInfos.append(" 序号异常,succeedCount=\(self?.succeedCount ?? 0),order=\(model.order)")
//                        break
//                    }
//                }else{
//                    errInfos.append("返回错误码:errCode=\(model.errCode),order=\(model.order)")
//                    break
//                }
//            }
//            
//            if errInfos.count > 0{
//                SVProgressHUD.showError(withStatus: errInfos)
//                
//            }else{
//                if let sucCount = self?.succeedCount, let totalCount = self?.totalPackCount {
//                    if sucCount < totalCount {
//                        //继续请求
//                        self?.reqDatas(dataId: dataId, packOrder: sucCount)
//                    }else{
//                        //已经完成
//                        SVProgressHUD.showSuccess(withStatus: "完成")
//                        if let gpsData = self?.fileData{
//                            
//                            //存储原始数据
//                            self?._saveGPSData(gpsData: gpsData, fileName: "\(dataId).bin")
//                            
//                            //转为文本文件存储
//                            var txt = ""
//                            for index in 0 ..< gpsData.count {
//                                let tempStr = String.init(format: "%c", gpsData[index])
//                                txt.append(tempStr)
//                            }
//                            if let txtData = txt.data(using: .utf8) {
//                                self?._saveGPSData(gpsData: txtData, fileName: "\(dataId).txt")
//                            }
//                        }
//                    }
//                }else{
//                    SVProgressHUD.showError(withStatus: "控制器可能被销毁了")
//                }
//            }
//        }
    }
    
    
    private func _saveGPSData(gpsData:Data,fileName:String){
        let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
        if let `docPath` = docPath{
            let filePath = docPath + "/\(fileName)"
            let `gpsData` = NSData.init(data: gpsData)
            let saveResult = gpsData.write(toFile: filePath, atomically: false)
            print("保存gps文件:\(saveResult)")
        }
    }
}
